package com.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.community.entity.Activity;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.community.service.ActivityService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("activity")
public class ActivityController extends ApiController {

    @Resource
    private ActivityService activityService;

    @GetMapping("list")
    @ResponseBody
    public R selectAll(Page<Activity> page, Activity activity) {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();
        wrapper.eq(activity.getStatus() != null, "status", activity.getStatus());
        wrapper.like(activity.getTitle() != null, "title", activity.getTitle());
        wrapper.between(activity.getStartDate() != null && activity.getEndDate() != null,
                "start_date", activity.getStartDate(), activity.getEndDate());
        wrapper.orderByDesc("start_date");
        return success(this.activityService.page(page, wrapper));
    }

    @RequestMapping("activity_list")
    public String activity_list() {
        return "activity_list";
    }

    @RequestMapping("activity_add")
    public String toadd() {
        return "activity_add";
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @ResponseBody
    public R selectOne(@PathVariable Serializable id) {
        return success(this.activityService.getById(id));
    }

    /**
     * 修改数据
     *
     * @param activity 实体对象
     * @return 修改结果
     */
    @PutMapping("update")
    @ResponseBody
    public R update(Activity activity) {
        return success(this.activityService.updateById(activity));
    }

    /**
     * 新增数据
     *
     * @param activity 实体对象
     * @return 新增结果
     */
    @PostMapping("add")
    @ResponseBody
    public R insert(Activity activity) {
        System.out.println(activity.toString());
        activity.setCreatedDate(new Date());
        return success(this.activityService.save(activity));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping("delete")
    @ResponseBody
    public R delete(@RequestParam("idList") List<Long> idList) {
        System.out.println("idList===" + idList);
        return success(this.activityService.removeByIds(idList));
    }
}
